package com.huiyin.ui.moments;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.huiyin.AppContext;
import com.huiyin.R;
import com.huiyin.UIHelper;
import com.huiyin.api.CustomResponseHandler;
import com.huiyin.api.RequstClient;
import com.huiyin.api.URLs;
import com.huiyin.bean.MomentsCircleItem;
import com.huiyin.bean.MomentsShowItem;
import com.huiyin.bean.MomentsShowListBean;
import com.huiyin.bean.MomentsShowListBean.MomentsBannerItem;
import com.huiyin.common.widget.pulltorefresh.PullToRefreshBase;
import com.huiyin.common.widget.pulltorefresh.PullToRefreshBase.Mode;
import com.huiyin.common.widget.pulltorefresh.PullToRefreshBase.OnRefreshListener2;
import com.huiyin.common.widget.pulltorefresh.PullToRefreshListView;
import com.huiyin.ui.classic.HorizontialListView;
import com.huiyin.ui.moments.adapter.MomentsHSAdapter;
import com.huiyin.ui.moments.adapter.MomentsShowAdapter;
import com.huiyin.ui.moments.adapter.MomentsViewflowAdapter;
import com.huiyin.ui.user.LoginActivity;
import com.huiyin.utils.DialogUtil;
import com.huiyin.utils.ImageManager;
import com.huiyin.utils.StringUtils;
import com.huiyin.utils.Utils;
import com.huiyin.wight.viewflow.CircleFlowIndicator;
import com.huiyin.wight.viewflow.ViewFlow;
import com.huiyin.wight.viewflow.ViewFlow.ViewSwitchListener;
import com.jcvideoplayer.JCVideoPlayer;
import com.vCamera.ui.record.MediaRecorderActivity;
/**
 * 秀场fragment
 * @author zhyao
 *
 */
public class MomentsShowFragment extends Fragment implements ViewSwitchListener, OnClickListener, OnRefreshListener2<ListView>, OnScrollListener, OnItemClickListener {
	
	private static final String TAG = "MomentsShowFragment";
	
	private View rootView;
	
	/**头像**/
	private ImageView mHeadImg;
	
	/**秀一秀**/
	private TextView mShowTv;
	
	/**秀场列表头部**/
	private View mHeadView;
	
	/**广告轮换图布局**/
	private RelativeLayout mViewFlowLayout;
	
	/**广告轮换图**/
	private ViewFlow mViewFlow;
	
	/**广告轮换下标**/
	private CircleFlowIndicator mIndicator;
	
	/**水平滑动Listview**/
	private HorizontialListView mHorizontialListView;
	
	/** 无数据布局 **/
	private LinearLayout mNoDataLayout;
	
	/**秀场列表**/
	private PullToRefreshListView mShowList;
	
	/**banner列表adapter**/
	private MomentsViewflowAdapter mMomentViewflowAdapter;
	
	/**圈子列表adapter**/
	private MomentsHSAdapter mMomentsHSAdapter;
	
	/**秀场列表adapter**/
	private MomentsShowAdapter mMomentsShowAdapter;
	
	/**广告 list**/
	private ArrayList<MomentsBannerItem> bannerList;

	/**圈子 list**/
	private ArrayList<MomentsCircleItem> circleList;

	/**秀场 list**/
	private ArrayList<MomentsShowItem> showList;	
	
	/**分页： 当前页**/
	private int pageIndex = 1;
	
	/**分页： 每页大小**/
	private int pageSize = 10;
	
	/**分页： 总页数**/
	private int totalPageNum;
	
	/**判断是否需要刷新, 当无数据是切换viewpage则刷新发现**/
	private boolean isNeedRefresh;
	
	
	@Override
	public void onAttach(Activity activity) {
		Log.i(TAG, "onAttach");
		super.onAttach(activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.i(TAG, "onCreate");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		Log.i(TAG, "onCreateView");
		rootView = inflater.inflate(R.layout.fragment_moments_show, null);
		initView();
		initData();
		return rootView;
	}

	@Override
	public void onResume() {
		super.onResume();
		Log.i(TAG, "onResume");
		
		setHeadImg();
	}


    @Override
	public void onPause() {
        super.onPause();
       
    }
    
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
    	super.setUserVisibleHint(isVisibleToUser);
    	
    	if(isVisibleToUser) {
    		if(isNeedRefresh) {
    			initData();
    		}
    	}
    	else {
    		JCVideoPlayer.releaseAllVideos();
    	}
    }
    
    /**
     * 刷新数据
     */
    public void onRefreshData() {
    	Log.d(TAG, "onRefreshData");
    	initData();
    }
    
	/**
	 * 初始化控件
	 */
	private void initView() {
		
		//导航栏
		mHeadImg = (ImageView) rootView.findViewById(R.id.img_head);
		mShowTv = (TextView) rootView.findViewById(R.id.tv_show);
		
		mHeadImg.setOnClickListener(this);
		mShowTv.setOnClickListener(this);
		
		mHeadView = LayoutInflater.from(getActivity()).inflate(R.layout.view_show_list_header, null);
		mViewFlowLayout = (RelativeLayout) mHeadView.findViewById(R.id.gl_moments_show); 
		//设置广告轮换图
		mViewFlow = (ViewFlow) mHeadView.findViewById(R.id.vf_moments_show);
		mIndicator = (CircleFlowIndicator) mHeadView.findViewById(R.id.cfi_moments_show);
		//水平滑动列表
		mHorizontialListView = (HorizontialListView) mHeadView.findViewById(R.id.hv_moments_show);
		mHorizontialListView.setVisibility(View.VISIBLE);
	
		//无数据
		mNoDataLayout = (LinearLayout) rootView.findViewById(R.id.ll_no_data);
		
		//秀场列表
		mShowList = (PullToRefreshListView) rootView.findViewById(R.id.lv_moments_show);
		mShowList.setMode(Mode.BOTH);
		mShowList.getLoadingLayoutProxy().setLastUpdatedLabel(Utils.getCurrTiem());
		mShowList.getLoadingLayoutProxy().setPullLabel("往下拉更新数据...");
		mShowList.getLoadingLayoutProxy().setRefreshingLabel("正在载入中...");
		mShowList.getLoadingLayoutProxy().setReleaseLabel("放开更新数据...");
		mShowList.setOnRefreshListener(this);
		mShowList.getRefreshableView().setOnScrollListener(this);
		
		//添加头部
		mShowList.getRefreshableView().addHeaderView(mHeadView);
		
	}
	
	private void initData() {
		bannerList = new ArrayList<MomentsBannerItem>();
		circleList = new ArrayList<MomentsCircleItem>();
		showList = new ArrayList<MomentsShowItem>();
		pageIndex = 1;
		
		requestShowList(pageIndex, pageSize);
	}
	
	private void setHeadImg() {
		if(AppContext.mUserInfo != null) {
			ImageManager.Load(URLs.IMAGE_URL+ AppContext.mUserInfo.img, mHeadImg, ImageManager.headOptions);
		}
		else {
			mHeadImg.setImageResource(R.drawable.default_head);
		}
	}
	

	/**
	 * 下拉刷新
	 * @param refreshView
	 */
	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		Log.d(TAG, "onRefresh");
		JCVideoPlayer.releaseAllVideos();
		
		initData();
	}

	/**
	 * 上拉加载更多
	 * @param refreshView
	 */
	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		Log.d(TAG, "onLodeMore");
		pageIndex++;
		if(pageIndex <= totalPageNum) {
			requestShowList(pageIndex, pageSize);
		}
		else {
			//mShowList.setMode(Mode.PULL_FROM_START);
			new Handler().postDelayed(new Runnable() {
				
				@Override
				public void run() {
					mShowList.onRefreshComplete();
				}
			}, 100);
		}
	}
	
	/**
	 * 列表滑动监听
	 */
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
	}

	/**
	 * 列表滑动状态监听
	 */
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		
	}

	/**
	 * 广告轮换图切换
	 * @param view
	 * @param position
	 */
	@Override
	public void onSwitched(View view, int position) {
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		//头像
		case R.id.img_head:
			
			if (StringUtils.isEmpty(AppContext.getInstance().userId)) {
				// 判断登录
				Intent intent = new Intent(getActivity(), LoginActivity.class);
				startActivity(intent);
			}
			else {
				Intent intent = new Intent(getActivity(), MomentsActivity.class);
				startActivity(intent);
			}
			
			break;
		//秀一秀
		case R.id.tv_show:
			if (StringUtils.isEmpty(AppContext.getInstance().userId)) {
				// 判断登录
				Intent intent = new Intent(getActivity(), LoginActivity.class);
				startActivity(intent);
			}
			else {
				DialogUtil.showSelectMomentsMethodDialog(getActivity(), new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						switch (v.getId()) {
						case R.id.btn_show_goods:
							startActivity(new Intent(getActivity(), MomentsSelectGoodsActivity.class));
							break;
						case R.id.btn_show_camera:
							startActivity(new Intent(getActivity(), MomentsShowPictureActivity.class));
							break;
						case R.id.btn_show_video:
							startActivity(new Intent(getActivity(), MediaRecorderActivity.class));
							break;

						default:
							break;
						}
						
					}
				});
			}
			
			break;

		default:
			break;
		}
		
	}

	/**
	 * 横向列表圈子Item点击事件
	 */
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		
		//跳转圈子
		Intent intent = new Intent();
		intent.setClass(getActivity(), MomentsCircleActivity.class);
		intent.putExtra(MomentsCircleActivity.INTENT_KEY_CIRCLE_ID, circleList.get(position).getID());
		intent.putExtra(MomentsCircleActivity.INTENT_KEY_CIRCLE_NAME, circleList.get(position).getNAME());
		startActivity(intent);
		
	}
	
	/**
	 * 请求秀场首页数据
	 * @param pageIndex
	 * @param pageSize
	 */
	private void requestShowList(int pageIndex, int pageSize) {
		RequstClient.showList(pageIndex, pageSize, new CustomResponseHandler(getActivity()) {
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				
				MomentsShowListBean bean = MomentsShowListBean.explainJson(content, getActivity());
				
				// 成功
				if(bean.type == 1) {
					totalPageNum = bean.getTotalPageNum();
					try {
						refreshShowListData(bean);
					} catch (Exception e) {
						e.printStackTrace();
					}
					
				}
				// 失败
				else {
					UIHelper.showToast(bean.msg);
				}
			}
			
			@Override
			public void onFailure(String error, String errorMessage) {
				super.onFailure(error, errorMessage);

				setNoDataUI(true);
				
				mShowList.onRefreshComplete();
			}
		});
	}

	/**
	 * 刷新数据
	 * @param bean
	 */
	private void refreshShowListData(MomentsShowListBean bean) {
		if(bean.getBannerList() != null) {
			bannerList.addAll(bean.getBannerList());
		}
		if(bean.getCircleList() != null) {
			circleList.addAll(bean.getCircleList());
		}
		if(bean.getShowList() != null) {
			showList.addAll(bean.getShowList());
		}
		
		if(pageIndex == 1) {
			setAdapter();
		}
		
		setNoDataUI(bannerList.isEmpty() && circleList.isEmpty() && showList.isEmpty());
		
		mShowList.onRefreshComplete();
	}
	
	/**
	 * 设置列表adapter
	 */
	private void setAdapter() {

		mMomentViewflowAdapter = new MomentsViewflowAdapter(getActivity(), bannerList);
		mViewFlow.setAdapter(mMomentViewflowAdapter); // 对viewFlow添加图片
		mViewFlow.setmSideBuffer(bannerList.size());
		mViewFlow.setFlowIndicator(mIndicator);
		mViewFlow.setTimeSpan(5000);
		mViewFlow.setSelection(bannerList.size() * 10); // 设置初始位置
		if(bannerList.size() > 1) {
			mViewFlowLayout.setVisibility(View.VISIBLE);
			mViewFlow.startAutoFlowTimer();
			mIndicator.setVisibility(View.VISIBLE);
		}
		else if(bannerList.size() == 1) {
			mViewFlowLayout.setVisibility(View.VISIBLE);
			mViewFlow.stopAutoFlowTimer();
			mIndicator.setVisibility(View.GONE);
		}
		else {
			mViewFlowLayout.setVisibility(View.GONE);
		}
		mViewFlow.setOnViewSwitchListener(this);
		
		mMomentsHSAdapter = new MomentsHSAdapter(getActivity(), circleList);
		mHorizontialListView.setAdapter(mMomentsHSAdapter);
		mHorizontialListView.setOnItemClickListener(this);
		
		mMomentsShowAdapter = new MomentsShowAdapter(getActivity(), showList);
		mShowList.getRefreshableView().setAdapter(mMomentsShowAdapter);
	
	}  
	
	/**
	 * 无数据UI
	 * 
	 * @param flag
	 */
	private void setNoDataUI(boolean flag) {
		if (flag) {
			mNoDataLayout.setVisibility(View.VISIBLE);
			mShowList.setVisibility(View.GONE);
		} else {
			mNoDataLayout.setVisibility(View.GONE);
			mShowList.setVisibility(View.VISIBLE);
		}
		isNeedRefresh = flag;
	}

}
